//
//  PictureDownloadManger.m
//  bh
//
//  Created by lanou on 15/12/26.
//  Copyright © 2015年 lanou. All rights reserved.
//

#import "PictureDownloadManger.h"

static PictureDownloadManger *pictureDownload;


@implementation PictureDownloadManger


+ (PictureDownloadManger *)shareDownloadManger{
    
    static dispatch_once_t onceToKen;
    dispatch_once(&onceToKen, ^{
        pictureDownload = [[PictureDownloadManger alloc]init];
    });
    return pictureDownload;
}

- (void)createDownLloadWithUl:(NSString *)url fileName:(NSString *)fileName{
    
    self.fileName = fileName;
    //NSURLSessionConfiguration配置session
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL
                                                          URLWithString:url]];
    //设置下载类
    self.task = [session downloadTaskWithRequest:request];
    
    //开始下载
    [self.task resume];

}

//下载完毕
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
    
    
    NSString *caches= [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    
    //使用caches 文件夹路径拼接我们的文件名，在拼接后缀，这样可以设置好我们的打开方式以及最终路径
    NSString *filePath = [[caches stringByAppendingPathComponent:self.fileName]stringByAppendingString:@".png"];
    
    NSFileManager *manger = [NSFileManager defaultManager];
    
    [manger moveItemAtPath:location.path toPath:filePath error:nil];
    
    self.filePath = [self.fileName stringByAppendingString:@".png"];
    
    //发送一个通知(下载结束)
    [[NSNotificationCenter defaultCenter] postNotificationName:@"downloadOver" object:nil];
    
    NSLog(@"%@",self.filePath);
    
    //下载完毕后置空
    self.task = nil;

    
    
    
    
    
}










@end
